% filled = dineof(time,data,mask,...)
% run dineof from Matlab/Octave
% 
% 

function filled = dineof(data,varargin)

global DINEOF_EXEC

% default values

nev = 10;
neini = 1;
ncv = nev + 10;
tol = 1.0e-8;
nitemax = 300;
toliter = 1.0e-3;
rec = 1;
eof = 1;
norm = 0;
seed = 243435;
alpha = 0.;
numit = 3;
frac = 0.05;
dir = tempname;
time = [];
mask = [];

exec = DINEOF_EXEC;
if isempty(exec)  
  exec = getenv('DINEOF_EXEC')
  if isempty(exec)  
    exec = 'dineof';
  end 
end

prop = varargin;

for i=1:2:length(prop)
  if strcmp(prop{i},'nev')
    nev = prop{i+1};
  elseif strcmp(prop{i},'neini')
    neini = prop{i+1};
  elseif strcmp(prop{i},'tol')
    tol = prop{i+1};
  elseif strcmp(prop{i},'toliter')
    toliter = prop{i+1};
  elseif strcmp(prop{i},'rec')
    rec = prop{i+1};
  elseif strcmp(prop{i},'eof')
    eof = prop{i+1};
  elseif strcmp(prop{i},'norm')
    norm = prop{i+1};
  elseif strcmp(prop{i},'seed')
    seed = prop{i+1};
  elseif strcmp(prop{i},'alpha')
    alpha = prop{i+1};
  elseif strcmp(prop{i},'numit')
    numit = prop{i+1};
  elseif strcmp(prop{i},'dir')
    dir = prop{i+1};
  elseif strcmp(prop{i},'exec')
    exec = prop{i+1};
  elseif strcmp(prop{i},'time')
    time = prop{i+1};
  elseif strcmp(prop{i},'mask')
    mask = prop{i+1};
  elseif strcmp(prop{i},'frac')
    frac = prop{i+1};
  else
    error(['unkown argument ' prop{i}]);
  end 
end

if isempty(mask)
  mask = dineof_mask(data,frac);
end

d = [dir filesep];
mkdir(d);

gwrite([d 'data'],data);
gwrite([d 'mask'],mask);

if alpha > 0
  gwrite([d 'time'],time);
end



initfile = [d 'dineof.init'];
fid = fopen(initfile,'w');

fprintf(fid,'# inpput File for dineof\n');
fprintf(fid,'# created by the script %s\n',mfilename);
fprintf(fid,'data    = [''%s'']\n',[d 'data']);
fprintf(fid,'mask    = [''%s'']\n',[d 'mask']);
fprintf(fid,'nev     = %d\n',nev);
fprintf(fid,'neini   = %d\n',neini);
fprintf(fid,'ncv     = %d\n',ncv);
fprintf(fid,'tol     = %g\n',tol);
fprintf(fid,'nitemax = %d\n',nitemax);
fprintf(fid,'toliter = %g\n',toliter);
fprintf(fid,'rec     = %d\n',rec);
fprintf(fid,'eof     = %d\n',eof);
fprintf(fid,'norm    = %d\n',norm);
fprintf(fid,'Output  = ''%s''\n',[d]);
fprintf(fid,'results = [''%s'']\n',[d 'output']);
fprintf(fid,'seed    = %d\n',seed);


fprintf(fid,'alpha   = %g\n',alpha);
fprintf(fid,'numit   = %d\n',numit);

if alpha > 0
  fprintf(fid,'time    = ''%s''\n',[d 'time']);
end

fclose(fid);

cmd = sprintf('"%s" "%s"',exec,initfile);
disp(cmd)

system(cmd);

filled = gread([d 'output']);
